package com.dingwen.treasure.kettle.task.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.dingwen.treasure.kettle.entity.TaskLog;
import com.dingwen.treasure.kettle.enums.ExecuteResultEnum;
import com.dingwen.treasure.kettle.constant.TaskConstant;
import com.dingwen.treasure.kettle.service.TaskInfoService;
import com.dingwen.treasure.kettle.service.TaskLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 任务执行： 全局监听 （日志记录）
 *
 * @author dingwen
 * @date 2022/05/09
 */
@Component
@Slf4j
public class TaskLogListener implements JobListener {

    /**
     * 监听器名称
     */
    private static final String TASK_LOG_LISTENER = "定时任务执行监听";

    /**
     * 任务服务
     */
    private final TaskInfoService taskInfoService = SpringUtil.getBean(TaskInfoService.class);


    /**
     * 任务： 日志服务
     */
    private final TaskLogService takeLogService = SpringUtil.getBean(TaskLogService.class);


    @Override
    public String getName() {
        return TASK_LOG_LISTENER;
    }

    /**
     * 工作执行
     *
     * @param jobExecutionContext 工作执行上下文
     */
    @Override
    public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {

    }

    /**
     * 立即执行之前
     *
     * @param jobExecutionContext 工作执行上下文
     */
    @Override
    public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
    }

    /**
     * 定时任务执行之后： 记录日志
     *
     * @param jobExecutionContext 工作执行上下文
     * @param e                   e
     */
    @Override
    public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException e) {

        // jobDataMap
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        // 获取定时任务的id
        Long id = Long.valueOf(jobDataMap.get(TaskConstant.TASK_ID).toString());
        // 任务执行耗时
        Long consumerTime = System.currentTimeMillis() - Long.parseLong(jobDataMap.get(TaskConstant.EXECUTE_START_TIME).toString());

        TaskLog taskLog = TaskLog.builder()
                .activateTime(LocalDateTime.now())
                .consumerTime(consumerTime)
                .taskId(id)
                .build();

        if (ObjectUtil.isEmpty(e)) {
            // 执行成功
            taskInfoService.incrementForSuccess(id);
            taskLog.setExecuteResult(ExecuteResultEnum.SUCCESS);
        } else {
            // 执行失败
            taskLog.setRemark(e.getMessage()).setExecuteResult(ExecuteResultEnum.FAIL);

            taskInfoService.incrementForFail(id);
        }
        // 存储日志
        takeLogService.save(taskLog);

    }
}
